package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"shop/consts"
	"shop/pkg"
	"strconv"
	"time"

	"net/http"
	"shop/api/request"
	"shop/initernal/dao"
	"shop/initernal/model"
)

func RegisterUser(c *gin.Context) {
	var req request.AddUser
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}
	user := model.User{
		Password: req.Password,
		Email:    req.Email,
	}

	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "注册新用户失败",
			"data":    nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "注册新用户成功",
		"data":    user,
	})

}

func LoginUser(c *gin.Context) {
	var req request.AddUser
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "取值失败",
			"data":    err.Error(),
		})
		return
	}
	var data model.User
	fields := dao.GetOneByFields(&model.User{
		Email: req.Email,
	}, &data)

	if !fields {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "账号或密码不正确",
			"data":    nil,
		})
		return
	}
	if data.Password != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "账号或密码不正确",
			"data":    nil,
		})
		return
	}

	token, err := pkg.NewJWT(consts.JWT_SECRETKEY).CreateToken(pkg.CustomClaims{
		ID:             data.Id,
		StandardClaims: jwt.StandardClaims{Audience: strconv.FormatInt(time.Now().Unix()+86400, 10)},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "token生成失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "用户登录成功",
		"data":    token,
	})

}

func Test(c *gin.Context) {
	ui := c.GetUint("userId")
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "解析参数为",
		"data":    ui,
	})
}
